package demo.android.com.mvpdemo.RxJava;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * Created by Vya on 2018/1/28.
 */

public abstract class Schedulers {
    static Schedulers IO;
    static Schedulers Main_Thread;

    static {
        IO = new IOSchedulers();
        Main_Thread = new MainSchedulers(new Handler(Looper.getMainLooper()));
    }
    public static Schedulers io() {
       return IO;
    }

    public abstract void scheduleDirect(Runnable runnable);

    public static Schedulers mainThread() {
        return Main_Thread;
    }


    private static class IOSchedulers extends Schedulers {
        ExecutorService service;
        public IOSchedulers(){
            service =  Executors.newScheduledThreadPool(1, new ThreadFactory() {
                @Override
                public Thread newThread(@NonNull Runnable r) {
                    return new Thread(r);
                }
            });
        }
        @Override
        public void scheduleDirect(Runnable runnable) {
            service.execute(runnable);
        }
    }

    private static class MainSchedulers extends Schedulers {
        private Handler handler;
        public MainSchedulers(Handler handler){
            this.handler = handler;
        }
        @Override
        public void scheduleDirect(Runnable runnable) {
            Message message = Message.obtain(handler,runnable);//这个使用了享元设计模式（用于复用对象的设计模式）

            handler.sendMessage(message);
        }
    }
}
